#pragma once
#include <iostream>
#include <sys/select.h>
#include <functional>
#include "sock.hpp"
#include "err.hpp"

namespace selectServer
{
    using func_t = std::function<std::string (const std::string&)>;
    class SelectServer
    {
        const static int defaultport = 8080;
        const static int default_val = -1;                  // fd数组的默认值
        const static int default_size = sizeof(fd_set) * 8; // select可以管理的文件描述符个数
    public:
        SelectServer(func_t cb, int port = defaultport) : _port(port), _listensock(-1), _fdarray(nullptr) ,_cb(cb)
        {
        }
        ~SelectServer()
        {
            close(_listensock);
            delete[] _fdarray;
        }
        void initServer()
        {

            // 1.创建套接字
            _listensock = Sock::Socket();

            // 1.5取消time_wait状态的绑定冷却时间
            int opt = 1;
            setsockopt(_listensock, SOL_SOCKET, SO_REUSEADDR | SO_REUSEPORT, &opt, sizeof(opt));

            // 2.绑定ip和端口
            Sock::Bind(_listensock, _port);

            // 3.设置监听状态
            Sock::Listen(_listensock);

            // 4.初始化select数组
            _fdarray = new int[default_size];
            for (int i = 0; i < default_size; ++i)
            {
                _fdarray[i] = default_val;
            }
            _fdarray[0] = _listensock;
        }

        void Accepter()
        {

            // 处理监听事件
            std::string clientip;
            uint16_t clientport;
            // 不会等待，直接获取连接
            int sock = Sock::Accept(_listensock, &clientip, &clientport);
            if (sock >= 0)
            {
                logMessage(NORMAL, "accept a new client, clientip: %s, clientport: %d", clientip.c_str(), clientport);
            }
            int i = 0;
            for (; i < default_size; ++i)
            {
                if (_fdarray[i] == default_val)
                {
                    _fdarray[i] = sock;
                    break;
                }
            }
            if (i == default_size) // 说明服务器压力太大，丢弃新的连接套接字，等服务器缓存过来后，需要重新连接
            {
                close(sock);
                return;
            }
            Print();
        }

        //处理客户端连接请求
        void Recver(int fdIndex)
        {
            char buffer[1024];
            //1.接受请求
            ssize_t n = recv(_fdarray[fdIndex], buffer, sizeof(buffer) - 1, 0);
            if(n > 0)
            {
                buffer[n] = 0;
            }
            else if(0 == n)
            {
                close(_fdarray[fdIndex]);
                _fdarray[fdIndex] = default_val;
                logMessage(NORMAL, "client quit");
                return;
            }
            else
            {
                close(_fdarray[fdIndex]);
                _fdarray[fdIndex] = default_val;
                logMessage(ERROR, "client quit err string: %s", strerror(errno));
                return;
            }
            
            std::cout << "echo# " << buffer << std::endl;

            //暂时不考虑发送的等待问题     ----bug-----   select处理起来比较麻烦
            std::string response;
            response = _cb(buffer);
            write(_fdarray[fdIndex], response.c_str(), response.size());
        }


        //处理select监视成功后的新任务
        void HandlerEvent(fd_set fds)
        {
            for (int i = 0; i < default_size; ++i)
            {
                if(_fdarray[i] == default_val)  continue; //过滤无效的fd

                
                //处理监听事件
                if(FD_ISSET(_fdarray[i], &fds) && _fdarray[i] == _listensock)
                {
                    Accepter();
                }
                else if(FD_ISSET(_fdarray[i], &fds)) //处理客户端请求
                {
                    Recver(i); 
                }
                else
                {
                    // ......
                }


            }
        }
        void Print()
        {
            std::cout << "fd list: ";
            for (int i = 0; i < default_size; ++i)
            {
                if (_fdarray[i] != default_val)
                    std::cout << " " << _fdarray[i] << " ";
            }
            std::cout << std::endl;
        }
        void start()
        {

            for (;;)
            {

                fd_set rfds;
                FD_ZERO(&rfds);

                // struct timeval tm = {2, 0};
                int maxfd = _fdarray[0];
                for (int i = 0; i < default_size; ++i)
                {
                    if (_fdarray[i] != default_val)
                    {
                        FD_SET(_fdarray[i], &rfds);
                        if (_fdarray[i] > maxfd)
                            maxfd = _fdarray[i];
                    }
                }
                // int n = select(_listensock + 1, &rfds, nullptr, nullptr, &tm);  //后面四个参数都是输入输出型参数 ？to do
                // int n = select(_listensock + 1, &rfds, nullptr, nullptr, nullptr); // 阻塞式调用
                int n = select(maxfd + 1, &rfds, nullptr, nullptr, nullptr); // 阻塞式调用

                // 一般我们使用select，需要程序员自定义一个文件描述符数组来维护select监控的数组,select技术的缺点
                switch (n)
                {
                case 0:
                    logMessage(NORMAL, "timeout....");
                    break;
                case -1:
                    // 调用失败了
                    logMessage(ERROR, "select err, code: %d  errstr: %s", errno, strerror(errno));
                    break;
                default:
                    // 说明事件就绪了
                    logMessage(NORMAL, "have a new message");
                    HandlerEvent(rfds);
                    break;
                }
            }
        }

    private:
        int _listensock;
        int _port;
        func_t _cb; //回调方法：由上层提供的业务逻辑
        int *_fdarray; // select维护的数组
    };
}